package com.hnao.serialport

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import com.wsm.hidlib.HIDManager
import com.wsm.hidlib.callback.HIDDataListener
import com.wsm.hidlib.callback.HIDOpenListener
import com.wsm.hidlib.constant.ConnectCostant

/**
 * @Author caow
 * 2025/2/19
 */
object SerialPortHidManager {

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                val result = msg.obj as String
                Log.i("caow", "handleMessage: $result")
                SerialPortCallbackListener.listener?.invoke(result)
            }
        }
    }

    fun initHID(context: Context) {
        HIDManager.getInstance().openHID(context, object : HIDOpenListener {
            override fun openSuccess(openSuccessStatus: Int) {
                if (openSuccessStatus == ConnectCostant.USB_CONNECT) {
                    Log.i("caow", "连接USB")
                } else if (openSuccessStatus == ConnectCostant.COMMUNICATION_OPEN) {
                    Log.i("caow", "通讯建立")
                }
            }

            override fun openError(openErrorStatus: Int) {
                if (openErrorStatus == ConnectCostant.USB_DISCONNECT) {
                    Log.i("caow", "断开USB")
                } else if (openErrorStatus == ConnectCostant.COMMUNICATION_CLOSE) {
                    Log.i("caow", "通讯断开")
                }
            }
        }, object : HIDDataListener {
            override fun onDataReceived(status: Byte, dataMessage: String) {
                if (!TextUtils.isEmpty(dataMessage)) {
                    val result = dataMessage
                    Log.i(
                        "caow",
                        "onDataReceived: length:" + dataMessage.length + "   content:" + result
                    )
                    val message = Message.obtain()
                    message.what = 1
                    message.obj = result
                    handler.sendMessage(message)
                }
            }

            override fun onOriginalDataReceived(b: Byte, bytes: ByteArray, i: Int) {
            }
        })
    }

    fun closeHID() {
        HIDManager.getInstance().closeHID()
    }


}